import React, { useState, useEffect } from 'react';
import { 
    Button, 
    Switch, 
    Select, 
    Spin, 
    Typography, 
    Card, 
    Space, 
    Divider,
    message,
    Alert
} from 'antd';
import { 
    CloseOutlined, 
    BulbOutlined, 
    RobotOutlined, 
    UserOutlined,
    ThunderboltOutlined,
    CheckCircleOutlined
} from '@ant-design/icons';
// Using a simpler approach for markdown rendering
const renderMarkdown = (text: string) => {
    if (!text) return '';
    // Simple markdown parsing for common elements
    return text
        .replace(/\n\n/g, '<br/><br/>')
        .replace(/\n/g, '<br/>')
        .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.+?)\*/g, '<em>$1</em>')
        .replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
        .replace(/^# (.+)$/gm, '<h1>$1</h1>')
        .replace(/^## (.+)$/gm, '<h2>$1</h2>')
        .replace(/^### (.+)$/gm, '<h3>$1</h3>');
};
import { fetchGenerateAIContent } from '../service';
// Using inline styles instead of external CSS to avoid service worker issues
const styles = {
  sidePanel: {
    position: 'fixed',
    top: 0,
    right: 0,
    width: '350px',
    height: '100vh',
    backgroundColor: '#fff',
    boxShadow: '-8px 0 32px rgba(0, 0, 0, 0.24)',
    zIndex: 999999,
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden',
    transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
    borderLeft: '1px solid #e1e5e9'
  },
  header: {
    padding: '24px',
    borderBottom: '1px solid #e1e5e9',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    minHeight: '80px'
  },
  headerTitle: {
    color: '#fff',
    margin: 0,
    fontSize: '18px',
    fontWeight: '600'
  },
  closeButton: {
    background: 'transparent',
    border: 'none',
    cursor: 'pointer',
    color: '#fff',
    padding: '8px',
    borderRadius: '6px',
    transition: 'background-color 0.2s ease'
  },
  content: {
    padding: '20px',
    overflowY: 'auto',
    flex: 1,
    backgroundColor: '#f8fafc'
  },
  successIcon: {
    fontSize: '48px',
    color: '#52c41a',
    marginBottom: '16px'
  },
  markdownContent: {
    padding: '20px',
    borderRadius: '12px',
    backgroundColor: '#ffffff',
    maxHeight: '400px',
    overflowY: 'auto',
    border: '1px solid #e1e5e9',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
    fontSize: '14px',
    lineHeight: '1.6'
  },
  loadingContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '40px 20px',
    backgroundColor: '#ffffff',
    borderRadius: '12px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)'
  },
  loadingText: {
    marginTop: '16px',
    color: '#667eea',
    fontSize: '14px',
    fontWeight: '500'
  },
  // New styles for enhanced components
  mindModelCard: {
    marginBottom: '20px',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    border: 'none',
    borderRadius: '12px',
    boxShadow: '0 4px 15px rgba(102, 126, 234, 0.2)'
  },
  mindModelHeader: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '16px',
    fontSize: '14px',
    fontWeight: '600',
    color: 'white'
  },
  switchContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: '16px',
    padding: '12px 16px',
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: '8px',
    border: '1px solid rgba(255, 255, 255, 0.2)'
  },
  switchLabel: {
    color: 'white',
    fontSize: '14px',
    fontWeight: '500',
    display: 'flex',
    alignItems: 'center'
  },
  selectStyle: {
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderRadius: '8px',
    border: '1px solid rgba(255, 255, 255, 0.3)'
  },
  generateButton: {
    background: 'linear-gradient(135deg, #52c41a 0%, #73d13d 100%)',
    border: 'none',
    borderRadius: '8px',
    height: '40px',
    fontWeight: '600',
    boxShadow: '0 2px 8px rgba(82, 196, 26, 0.3)',
    transition: 'all 0.3s ease'
  },
  aiResultCard: {
    marginTop: '20px',
    background: 'linear-gradient(135deg, #13c2c2 0%, #36cfc9 100%)',
    border: 'none',
    borderRadius: '12px',
    boxShadow: '0 4px 15px rgba(19, 194, 194, 0.2)'
  },
  aiResultHeader: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '12px',
    fontSize: '14px',
    fontWeight: '600',
    color: 'white'
  }
};

const { Title, Text } = Typography;
const { Option } = Select;

interface MindModel {
    value: string | null;
    text: string;
    isDefault: boolean | null;
}

interface SidePanelProps {
    visible: boolean;
    onClose: () => void;
    infoGuid: string;
    userGuid: string;
}

export const SidePanel: React.FC<SidePanelProps> = ({ 
    visible, 
    onClose, 
    infoGuid, 
    userGuid 
}) => {
    const [isPersonalMode, setIsPersonalMode] = useState(true);
    const [userMindModels, setUserMindModels] = useState<MindModel[]>([]);
    const [systemMindModels, setSystemMindModels] = useState<MindModel[]>([]);
    const [selectedModel, setSelectedModel] = useState<string>('');
    const [loading, setLoading] = useState(false);
    const [generating, setGenerating] = useState(false);
    const [generatedContent, setGeneratedContent] = useState<string>('');
    const [collectSuccess, setCollectSuccess] = useState(false);

    // Load user mind models
    const loadUserMindModels = async () => {
        try {
            setLoading(true);
            console.log('开始加载用户思维模型 - Starting to load user mind models');
            
            // 使用消息传递从 background 脚本获取最新数据
            console.log('发送消息到 background 脚本获取思维模型 - Sending message to background script');
            
            // 创建一个 Promise 来处理消息响应
            const response = await new Promise<any>((resolve, reject) => {
                chrome.runtime.sendMessage(
                    { type: 'GET_USER_MIND_MODELS' },
                    (response) => {
                        if (chrome.runtime.lastError) {
                            console.error('发送消息错误 - Message sending error:', chrome.runtime.lastError);
                            reject(chrome.runtime.lastError);
                        } else {
                            console.log('收到 background 响应 - Received background response:', response);
                            resolve(response);
                        }
                    }
                );
            });
            
            console.log('思维模型响应 - Mind models response:', response);
            
            if (response && response.success) {
                console.log('原始响应数据 - Raw response data:', response.data);
                
                // 处理可能的数据结构差异
                let mindModels = [];
                
                if (response.data) {
                    if (Array.isArray(response.data)) {
                        // 直接是数组
                        mindModels = response.data;
                        console.log('响应数据是数组 - Response data is array, length:', mindModels.length);
                    } else if (typeof response.data === 'object') {
                        // 如果是对象但包含数组
                        console.log('响应数据是对象 - Response data is object with keys:', Object.keys(response.data));
                        
                        // 尝试不同的方式提取数组
                        if (Array.isArray(response.data[0])) {
                            mindModels = response.data[0];
                            console.log('从对象[0]提取数组 - Extracted array from object[0], length:', mindModels.length);
                        } else {
                            // 尝试将对象值转为数组
                            const values = Object.values(response.data);
                            if (values.length > 0) {
                                if (Array.isArray(values[0])) {
                                    mindModels = values[0];
                                    console.log('从对象值提取数组 - Extracted array from object values[0], length:', mindModels.length);
                                } else if (Array.isArray(values)) {
                                    mindModels = values;
                                    console.log('使用对象值作为数组 - Using object values as array, length:', mindModels.length);
                                }
                            }
                        }
                    }
                }
                
                console.log('最终解析的思维模型数据 - Final parsed mind models data:', mindModels);
                
                if (mindModels.length > 0) {
                    // 设置思维模型数据
                    setUserMindModels(mindModels);
                    
                    // 设置默认选择
                    const defaultModel = mindModels.find((model: MindModel) => model.isDefault);
                    console.log('默认模型 - Default model:', defaultModel);
                    
                    if (defaultModel && defaultModel.value) {
                        console.log('设置默认选中模型 - Setting default selected model:', defaultModel.value);
                        setSelectedModel(defaultModel.value);
                    } else if (mindModels.length > 0 && mindModels[0].value) {
                        // 如果没有默认模型但有数据，选择第一个
                        console.log('没有默认模型，选择第一个 - No default model, selecting first one:', mindModels[0].value);
                        setSelectedModel(mindModels[0].value);
                    } else {
                        console.warn('没有有效的思维模型数据 - No valid mind model data');
                    }
                } else {
                    console.warn('解析后没有思维模型数据 - No mind models data after parsing');
                }
            } else {
                // 处理错误
                const errorMsg = response?.message || 'Failed to load mind models';
                console.error('获取思维模型失败 - Failed to get mind models:', errorMsg);
                message.error(`Failed to load mind models: ${errorMsg}`);
                
                // 尝试使用缓存数据作为后备
                console.log('尝试使用缓存数据 - Trying to use cached data');
                const cachedResult = await chrome.storage.local.get('userMindModels');
                console.log('缓存结果原始数据 - Raw cached result:', cachedResult);
                
                // 处理可能的数据结构差异
                let cachedModels = [];
                if (cachedResult && cachedResult.userMindModels) {
                    if (Array.isArray(cachedResult.userMindModels)) {
                        cachedModels = cachedResult.userMindModels;
                        console.log('缓存数据是数组 - Cached data is array, length:', cachedModels.length);
                    } else if (typeof cachedResult.userMindModels === 'object') {
                        // 如果是对象但具有数组属性
                        const keys = Object.keys(cachedResult.userMindModels);
                        console.log('缓存数据是对象 - Cached data is object with keys:', keys);
                        
                        // 尝试提取数组数据
                        if (Array.isArray(cachedResult.userMindModels[0])) {
                            cachedModels = cachedResult.userMindModels[0];
                            console.log('从对象[0]提取数组 - Extracted array from object[0], length:', cachedModels.length);
                        } else {
                            // 尝试将对象值转为数组
                            const values = Object.values(cachedResult.userMindModels);
                            if (values.length > 0 && Array.isArray(values[0])) {
                                cachedModels = values[0];
                                console.log('从对象值提取数组 - Extracted array from object values, length:', cachedModels.length);
                            }
                        }
                    }
                }
                
                if (cachedModels && Array.isArray(cachedModels) && cachedModels.length > 0) {
                    console.log('使用缓存的思维模型数据 - Using cached mind models data, count:', cachedModels.length);
                    setUserMindModels(cachedModels);
                    
                    // 设置默认选择
                    const defaultModel = cachedModels.find((model: MindModel) => model.isDefault);
                    if (defaultModel && defaultModel.value) {
                        setSelectedModel(defaultModel.value);
                    } else if (cachedModels.length > 0 && cachedModels[0].value) {
                        setSelectedModel(cachedModels[0].value);
                    }
                    
                    message.warning('Using cached mind models data. Some information may not be up to date.');
                }
            }
        } catch (error) {
            console.error('加载用户思维模型出错 - Error loading user mind models:', error);
            message.error('Failed to load user mind models');
            
            // 尝试使用缓存数据作为后备
            try {
                const cachedResult = await chrome.storage.local.get('userMindModels');
                const cachedModels = cachedResult.userMindModels;
                
                if (cachedModels && Array.isArray(cachedModels) && cachedModels.length > 0) {
                    console.log('出错后使用缓存数据 - Using cached data after error, count:', cachedModels.length);
                    setUserMindModels(cachedModels);
                    
                    // 设置默认选择
                    const defaultModel = cachedModels.find((model: MindModel) => model.isDefault);
                    if (defaultModel && defaultModel.value) {
                        setSelectedModel(defaultModel.value);
                    } else if (cachedModels.length > 0 && cachedModels[0].value) {
                        setSelectedModel(cachedModels[0].value);
                    }
                    
                    message.warning('Using cached mind models data due to an error.');
                }
            } catch (cacheError) {
                console.error('读取缓存数据失败 - Failed to read cached data:', cacheError);
            }
        } finally {
            setLoading(false);
        }
    };

    // Load system mind models
    const loadSystemMindModels = async () => {
        try {
            setLoading(true);
            console.log('开始加载系统思维模型 - Starting to load system mind models');
            
            // 使用消息传递从 background 脚本获取最新数据
            console.log('发送消息到 background 脚本获取系统思维模型 - Sending message to background script');
            
            // 创建一个 Promise 来处理消息响应
            const response = await new Promise<any>((resolve, reject) => {
                chrome.runtime.sendMessage(
                    { type: 'GET_SYSTEM_MIND_MODELS' },
                    (response) => {
                        if (chrome.runtime.lastError) {
                            console.error('发送消息错误 - Message sending error:', chrome.runtime.lastError);
                            reject(chrome.runtime.lastError);
                        } else {
                            console.log('收到 background 响应 - Received background response:', response);
                            resolve(response);
                        }
                    }
                );
            });
            
            console.log('系统思维模型响应 - System mind models response:', response);
            
            if (response && response.success) {
                setSystemMindModels(response.data || []);
                // 设置默认选择（如果有）
                const defaultModel = response.data?.find((model: MindModel) => model.isDefault);
                if (defaultModel && defaultModel.value) {
                    setSelectedModel(defaultModel.value);
                }
            } else {
                // 如果消息传递失败，尝试从本地存储获取缓存数据
                console.log('尝试从缓存获取系统思维模型 - Trying to get system mind models from cache');
                const cachedData = await chrome.storage.local.get('systemMindModels');
                if (cachedData && cachedData.systemMindModels && cachedData.systemMindModels.length > 0) {
                    console.log('使用缓存的系统思维模型 - Using cached system mind models');
                    setSystemMindModels(cachedData.systemMindModels);
                    // 设置默认选择（如果有）
                    const defaultModel = cachedData.systemMindModels.find((model: MindModel) => model.isDefault);
                    if (defaultModel && defaultModel.value) {
                        setSelectedModel(defaultModel.value);
                    }
                    // 显示警告消息
                    message.warning('Using cached system mind models. Data may not be up to date.');
                } else {
                    message.error(response?.message || 'Failed to load system mind models');
                }
            }
        } catch (error) {
            console.error('加载系统思维模型错误 - Error loading system mind models:', error);
            message.error('Failed to load system mind models');
            
            // 尝试从本地存储获取缓存数据
            try {
                console.log('尝试从缓存获取系统思维模型 - Trying to get system mind models from cache');
                const cachedData = await chrome.storage.local.get('systemMindModels');
                if (cachedData && cachedData.systemMindModels && cachedData.systemMindModels.length > 0) {
                    console.log('使用缓存的系统思维模型 - Using cached system mind models');
                    setSystemMindModels(cachedData.systemMindModels);
                    // 显示警告消息
                    message.warning('Using cached system mind models. Data may not be up to date.');
                }
            } catch (cacheError) {
                console.error('读取缓存失败 - Failed to read cache:', cacheError);
            }
        } finally {
            setLoading(false);
        }
    };

    // Generate AI content
    const generateAIContent = async () => {
        if (!selectedModel) {
            message.warning('Please select a mind model first');
            return;
        }

        try {
            setGenerating(true);
            
            // 从chrome storage获取用户信息
            const result = await chrome.storage.local.get('user');
            const user = result.user;
            
            if (!user) {
                message.error('User not logged in');
                return;
            }
            
            const apiResult = await fetchGenerateAIContent({
                userGuid: user.userGuid,
                infoGuid: infoGuid,
                mindPromptGuids: [selectedModel],
                accessToken: user.accessToken
            });
            
            if (apiResult.isSuccess) {
                setGeneratedContent(apiResult.data || '');
                message.success('AI content generated successfully!');
            } else {
                message.error('Failed to generate AI content');
            }
        } catch (error) {
            message.error('Failed to generate AI content');
        } finally {
            setGenerating(false);
        }
    };

    // Handle mode switch
    const handleModeSwitch = (checked: boolean) => {
        setIsPersonalMode(checked);
        setSelectedModel('');
        setGeneratedContent('');
        
        if (checked) {
            loadUserMindModels();
        } else {
            loadSystemMindModels();
        }
    };

    // Initialize component
    useEffect(() => {
        if (visible) {
            console.log('SidePanel 变为可见 - SidePanel became visible');
            setCollectSuccess(true);
            console.log('准备加载用户思维模型 - About to load user mind models');
            loadUserMindModels();
        }
    }, [visible]);
    
    // 监控思维模型数据变化
    useEffect(() => {
        console.log('用户思维模型数据更新 - User mind models updated:', userMindModels);
        console.log('用户思维模型数量 - User mind models count:', userMindModels.length);
    }, [userMindModels]);
    
    useEffect(() => {
        console.log('系统思维模型数据更新 - System mind models updated:', systemMindModels);
        console.log('系统思维模型数量 - System mind models count:', systemMindModels.length);
    }, [systemMindModels]);

    const currentModels = isPersonalMode ? userMindModels : systemMindModels;

    if (!visible) return null;

    return (
        <div style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(0, 0, 0, 0.3)',
            zIndex: 999998,
            display: 'flex',
            justifyContent: 'flex-end'
        }}>
            <div style={styles.sidePanel as React.CSSProperties}>
                <div style={styles.header as React.CSSProperties}>
                    <h2 style={styles.headerTitle as React.CSSProperties}>InfoKeyMind</h2>
                    <Button 
                        icon={<CloseOutlined />} 
                        onClick={onClose} 
                        style={styles.closeButton as React.CSSProperties}
                        type="text"
                    />
                </div>
                
                <div style={styles.content as React.CSSProperties}>
                    {/* Success Status */}
                    {collectSuccess && (
                        <Alert
                            message="Collection Successful"
                            description="Page content has been successfully collected and processed."
                            type="success"
                            icon={<CheckCircleOutlined />}
                            showIcon
                            style={{ 
                                marginBottom: '20px',
                                borderRadius: '8px',
                                border: '1px solid #b7eb8f'
                            }}
                        />
                    )}

                    {/* Personal/System Mind Models */}
                    <Card 
                        size="small" 
                        style={styles.mindModelCard as React.CSSProperties}
                    >
                        <div style={{ color: 'white' }}>
                            <div style={styles.mindModelHeader as React.CSSProperties}>
                                <span style={{ marginRight: '8px' }}>🧠</span>
                                <Typography.Text strong style={{ color: 'white' }}>Mind Models</Typography.Text>
                            </div>
                            
                            <div style={styles.switchContainer as React.CSSProperties}>
                                <div style={styles.switchLabel as React.CSSProperties}>
                                    <UserOutlined style={{ marginRight: '8px' }} />
                                    <span>Personal Models</span>
                                </div>
                                <Switch 
                                    checked={isPersonalMode}
                                    onChange={handleModeSwitch}
                                    size="small"
                                />
                                <div style={styles.switchLabel as React.CSSProperties}>
                                    <RobotOutlined style={{ marginRight: '8px' }} />
                                    <span>System Models</span>
                                </div>
                            </div>
                            
                            {/* Mind Model Selection */}
                            <Space direction="vertical" style={{ width: '100%' }} size="small">
                                {loading ? (
                                    <div style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        padding: '20px',
                                        backgroundColor: 'rgba(255, 255, 255, 0.1)',
                                        borderRadius: '8px'
                                    }}>
                                        <Spin size="small" style={{ marginRight: '8px' }} />
                                        <Typography.Text style={{ color: 'white' }}>Loading models...</Typography.Text>
                                    </div>
                                ) : (
                                    <Select
                                        value={selectedModel}
                                        onChange={setSelectedModel}
                                        placeholder="Choose a mind model"
                                        style={{
                                            width: '100%',
                                            ...styles.selectStyle
                                        }}
                                        options={currentModels.map(model => ({
                                            value: model.value,
                                            label: model.text
                                        }))}
                                    />
                                )}
                                
                                {/* Generate Button */}
                                <Button
                                    type="primary"
                                    icon={<ThunderboltOutlined />}
                                    onClick={generateAIContent}
                                    loading={generating}
                                    disabled={!selectedModel}
                                    style={{
                                        width: '100%',
                                        marginTop: '12px',
                                        ...styles.generateButton
                                    }}
                                >
                                    {generating ? 'Generating...' : 'Generate AI Analysis'}
                                </Button>
                            </Space>
                        </div>
                    </Card>

                    {/* AI Generated Content */}
                    {generatedContent && (
                        <Card
                            size="small"
                            style={styles.aiResultCard as React.CSSProperties}
                        >
                            <div style={{ color: 'white' }}>
                                <div style={styles.aiResultHeader as React.CSSProperties}>
                                    <span style={{ marginRight: '8px' }}>🤖</span>
                                    <Typography.Text strong style={{ color: 'white' }}>AI Analysis Result</Typography.Text>
                                </div>
                                <div
                                    style={styles.markdownContent as React.CSSProperties}
                                    dangerouslySetInnerHTML={{ __html: renderMarkdown(generatedContent) }}
                                />
                            </div>
                        </Card>
                    )}
                </div>
            </div>
        </div>
    );
};

export default SidePanel;
